﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using Mabalacat.CPS.DataAccess.Repositories;
using Mabalacat.CPS.DataAccess.Base;
using Mabalacat.CPS.DataAccess.DataObjects;
using Mabalacat.CPS.BusinessLogic.Services.Interfaces;

namespace Mabalacat.CPS.BusinessLogic.Services
{
    public class UserService : IUserService
    {
        #region Fields
        
        private DbContext _dbContext;        
        private IUserRepository _userRepository;
         private IDatabaseFactory _dbFactory;
        #endregion
        
        #region ctor

        public UserService()
            : this(new DatabaseFactory())
        {
            
        }

        public UserService(IDatabaseFactory dbFactory)
        {
           if (dbFactory == null) throw new ArgumentNullException("dbFactory");
            _dbFactory = dbFactory;
            DbContext = dbFactory.Get();     
        }
        
        private DbContext DbContext
        {
            get { return _dbContext; }
            set 
            { 
                _dbContext = value;
                _userRepository = new UserRepository(_dbContext);
            }
        }

        #endregion

        #region Implementation of IUserService    
        
        public User GetById(int id)
        {
            return _userRepository.GetById(id);
        }

        public User GetByUserName(string username)
        {
            return _userRepository.Get(user => user.UserName.Equals(username));                
        }

        public User GetByUserNameAndPassword(string username, string password)
        {
            return _userRepository.Get(user => user.UserName.Equals(username) && user.Password.Equals(password));                
        }


        public IEnumerable<User> GetAll()
        {
            return _userRepository.GetAll();
        }

        public void AddToRole(User user, List<Role> roles)
        {
            throw new NotImplementedException();
        }
        public void Add(User user)
        {
            user.DateAdded = DateTime.Now;
            _userRepository.Add(user);
        }

        public void Update(User user)
        {
            _userRepository.Update(user);
        }

        public void Delete(int id)
        {
            var user = GetById(id);
            if (user != null)
                _userRepository.Delete(user);
        }
        public bool Save()
        {
            string message;
            _userRepository.Save(out message) ;
            return message == "Saved";
        }


        #endregion

        #region Private Methods
       
        #endregion



    }
}
